﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ChatManager : MonoBehaviour {

    Rect chatWindowRect = new Rect(0, 0, 0, 0);
    bool chatWindowInitialized = false;
    string userMessage = "";

    List<string> messageBuffer = new List<string>();
    public int maxMessages = 5;
    public bool setFocusToChatMesssageInput = false;

    bool chatEnabled = false;

    private enum ChatMessageType
    {
        UserMessage = 0,
        PlayerConnect = 1,
        PlayerDisconnect = 2
    }

    // Use this for initialization
	void Start () {

        print("Chat Manager Started");
        chatEnabled = (bool)(Preserver.Instance.Objects["chatEnabled"]);
        if (chatEnabled)
        {
            networkView.RPC("ReceiveChatMessage", RPCMode.All, "1" + Preserver.Instance.Objects["playerName"].ToString() + " has joined the game.");
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (!chatEnabled) return;

        if (!chatWindowInitialized)
        {
            chatWindowRect = new Rect(5, Screen.height - 145, Screen.width - 10, 140);
            chatWindowInitialized = true;
        }

        if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
        {
            // Not currently in chat, so focus the control.
            GUI.FocusWindow(0);
            setFocusToChatMesssageInput = true;
        }

	}

    void OnGUI()
    {
        if (!chatEnabled) return;

        if (chatWindowInitialized)
        {
            chatWindowRect = GUI.Window(0, chatWindowRect, OnChatWindowGUI, "Chat");
        }

    }

    void OnChatWindowGUI(int windowId)
    {
        if (Event.current.type == EventType.KeyDown && (Event.current.keyCode == KeyCode.Return))
        {
            if (GUI.GetNameOfFocusedControl() == "ChatInput")
            {
                // Currently in chat, so send the message.
                if (!string.IsNullOrEmpty(userMessage))
                {
                    userMessage = "0" + Preserver.Instance.Objects["playerName"].ToString() + ": " + userMessage;
                    networkView.RPC("ReceiveChatMessage", RPCMode.All, userMessage);
                    userMessage = string.Empty;
                }
                GUI.FocusControl(null);
            }
        }

        for (int i = 0; i < messageBuffer.Count; i++)
        {
            Color tint = Color.white;
            string message = messageBuffer[i].Substring(1);
            int messageTypeValue = int.Parse(messageBuffer[i][0].ToString());
            ChatMessageType messageType = (ChatMessageType)messageTypeValue;

            switch (messageType)
            {
                case ChatMessageType.UserMessage:
                    break;
                case ChatMessageType.PlayerConnect:
                    tint = Color.green;
                    break;
                case ChatMessageType.PlayerDisconnect:
                    tint = Color.red;
                    break;
            }

            GUI.color = tint;
            GUI.Label(new Rect(4, 17 + i * 20, Screen.width - 22, 24), message);

            GUI.color = Color.white;
        }

        GUI.SetNextControlName("ChatInput");
        userMessage = GUI.TextField(new Rect(4, 117, Screen.width - 22, 20), userMessage);
        if (setFocusToChatMesssageInput)
        {
            setFocusToChatMesssageInput = false;
            GUI.FocusControl("ChatInput");
        }
    }

    [RPC]
    void ReceiveChatMessage(string chatMessage)
    {
        if (!chatEnabled) return;

        while (messageBuffer.Count >= maxMessages)
        {
            messageBuffer.RemoveAt(0);
        }

        messageBuffer.Add(chatMessage);
    }

    [RPC]
    void SetPlayerName(int playerIndex, string playerName)
    {
        GameObject gameController = GameObject.Find("GameController");
        NetworkDungeonController controllerComponent = gameController.GetComponent<NetworkDungeonController>();
        controllerComponent.SetPlayerName(playerIndex, playerName);
    }

}
